package yxy.game.pm2.bean.module;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RLock;
import org.redisson.api.RScoredSortedSet;

import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;

public class PayRankModule extends BaseGameRedisBean {

	//redis ------------------------------------------------------------------------
	
	public RScoredSortedSet<String> touch() {
		try {
			return RedisManager.client(redis()).getScoredSortedSet(key());
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取充值金额  单位分
	 * @param key
	 * @param value
	 * @return
	 */
	public static Double getValueByCode(String key) {
		RScoredSortedSet<String> zset;
		try {
			zset = RedisManager.client(redis()).getScoredSortedSet(String.format("PAY:SORT"));
			return zset.getScore(key);	
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/** 累加数据 */
	public void addAndSet(String key, long value) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				RLock lock = lock(key);
				try {
					if (lock.tryLock(10, 5, TimeUnit.SECONDS)) {
						RScoredSortedSet<String> zset = touch();
						Double pscore = zset.getScore(key);
						long ovalue = 0;
						if (pscore != null) {
							ovalue = pscore.longValue();
						}
						addScore(key, value + ovalue, zset);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		}).start();
	}
	
	protected void addScore(String key, long value) {
		addScore(key, value, touch());
	}

	private void addScore(String key, long value, RScoredSortedSet<String> zset) {
		zset.add(value, key);
	}
	
	private String key() {
		return String.format("PAY:SORT");
	}
	
	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key());
	}

	protected RLock lock() {
		RLock lock = redis().client().getFairLock(lockKey());
		return lock;
	}

	protected RLock lock(String key) {
		String lockkey = String.format("lock:%s", key());
		RLock lock = redis().client().getFairLock(lockkey);
		return lock;
	}
}
